package com.android.base.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/*
 *@ProjectName: AndroidCommon
 *@FileName: SerializeManager.java
 *@CreateTime: 2014-2-8 下午4:01:17
 *@Author: Sammie.Zhang
 *@Description:
 */
public class SerializeUtil {
	/**
	 * 序列化文件
	 * @param obj
	 * @param path
	 */
	public static void saveFile(Object obj, String path) {
		FileOutputStream fos = null;
		try {
			File f = new File(path);
			File parent = f.getParentFile();
			if (!parent.exists()) {
				parent.mkdirs();
			}
			fos = new FileOutputStream(path);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(obj);
			oos.flush();
			oos.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (null != fos) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 反序列化文件
	 * @param filepath
	 * @return
	 */
	public static Object loadFile(String filepath) {
		File f = null;
		FileInputStream fis = null;
		ObjectInputStream oin = null;
		try {
			f = new File(filepath);
			if (f.exists()) {
				fis = new FileInputStream(filepath);
				oin = new ObjectInputStream(fis);
				Object obj = oin.readObject();
				return obj;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (null != oin) {
					oin.close();
				}
				if (null != fis) {
					fis.close();
				}
			} catch (Exception e) {

			}
		}
		return null;
	}
}
